<template>
  <div class="perm-wrapper">
    <div class="perm-list-group">
      <div class="perm-list-group-title">
        工作台权限
        <a-button type="link" size="small" @click="toggleModule('workbench')">
          {{ isWorkbenchAllSelected ? '取消全选' : '全选' }}
        </a-button>
      </div>
      <div class="perm-list-item" v-for="item in permissions.workbench" :key="item.key || ''">
        <div class="perm-list-item-title">
          <a-checkbox v-if="item.key"
                      name="key"
                      :checked="selectedKeys.includes(item.key)"
                      @change="handleItemChange(item.key, item.actions, $event)">
            {{ item.title }}
          </a-checkbox>
        </div>
        <div class="perm-list-item-content" v-if="item.actions && item.actions.length > 0">
          <a-checkbox
              v-for="action in item.actions"
              :key="action"
              name="key"
              :checked="selectedKeys.includes(action)"
              @change="handleActionChange(item.key, action, $event)">
            {{ getPermActionText(action) }}
          </a-checkbox>
        </div>
      </div>
    </div>
    <div class="perm-list-group border-top">
      <div class="perm-list-group-title">
        管理后台权限
        <a-button type="link" size="small" @click="toggleModule('admin')">
          {{ isAdminAllSelected ? '取消全选' : '全选' }}
        </a-button>
      </div>
      <div class="perm-list-item" v-for="item in permissions.admin" :key="item.key || ''">
        <div class="perm-list-item-title">
          <a-checkbox
              v-if="item.key"
              name="key"
              :checked="selectedKeys.includes(item.key)"
              @change="handleItemChange(item.key, item.actions, $event)">
            {{ item.title }}
          </a-checkbox>
        </div>
        <div class="perm-list-item-content" v-if="item.actions && item.actions.length > 0">
          <a-checkbox
              v-for="action in item.actions"
              :key="action"
              name="key"
              :checked="selectedKeys.includes(action)"
              @change="handleActionChange(item.key, action, $event)">
            {{ getPermActionText(action) }}
          </a-checkbox>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getPermissions,getPermActionText } from "@/utils/permission.ts";
import { computed } from "vue";
import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface';

const permissions = getPermissions();
const selectedKeys = defineModel<string[]>('selectedKeys',{default:()=> []});

// 获取所有权限键值
const getAllPermissionKeys = computed(() => {
  const workbenchKeys = permissions.workbench.flatMap(item => {
    const keys: string[] = [];
    if (item.key) keys.push(item.key);
    if (item.actions) keys.push(...item.actions.filter(action => action));
    return keys;
  });

  const adminKeys = permissions.admin.flatMap(item => {
    const keys: string[] = [];
    if (item.key) keys.push(item.key);
    if (item.actions) keys.push(...item.actions.filter(action => action));
    return keys;
  });

  return {
    workbench: workbenchKeys,
    admin: adminKeys
  };
});

// 检查模块是否全选
const isWorkbenchAllSelected = computed(() => {
  return getAllPermissionKeys.value.workbench.every(key => selectedKeys.value.includes(key));
});

const isAdminAllSelected = computed(() => {
  return getAllPermissionKeys.value.admin.every(key => selectedKeys.value.includes(key));
});

// 模块全选/取消全选
const toggleModule = (module: 'workbench' | 'admin') => {
  const moduleKeys = getAllPermissionKeys.value[module];
  const isAllSelected = moduleKeys.every(key => selectedKeys.value.includes(key));
  
  if (isAllSelected) {
    // 取消全选
    selectedKeys.value = selectedKeys.value.filter(key => !moduleKeys.includes(key));
  } else {
    // 全选
    selectedKeys.value = [...new Set([...selectedKeys.value, ...moduleKeys])];
  }
};

// 处理项目复选框变化
const handleItemChange = (itemKey: string, actions: string[] | undefined, e: CheckboxChangeEvent) => {
  const checked = e.target.checked;
  
  if (checked) {
    // 选中项目及所有操作
    const newKeys = [...selectedKeys.value];
    if (!newKeys.includes(itemKey)) newKeys.push(itemKey);
    if (actions) {
      actions.forEach(action => {
        if (action && !newKeys.includes(action)) newKeys.push(action);
      });
    }
    selectedKeys.value = newKeys;
  } else {
    // 取消选中项目及所有操作
    selectedKeys.value = selectedKeys.value.filter(
      key => key !== itemKey && (!actions || !actions.includes(key))
    );
  }
};

// 处理操作复选框变化
const handleActionChange = (itemKey: string | undefined, actionKey: string, e: CheckboxChangeEvent) => {
  const checked = e.target.checked;
  
  if (checked) {
    // 选中操作
    if (!selectedKeys.value.includes(actionKey)) {
      selectedKeys.value = [...selectedKeys.value, actionKey];
    }
  } else {
    // 取消选中操作
    selectedKeys.value = selectedKeys.value.filter(key => key !== actionKey);
    
    // 如果项目所有操作都被取消，则取消项目
    if (itemKey) {
      const item = [...permissions.workbench, ...permissions.admin].find(i => i.key === itemKey);
      if (item?.actions?.every(action => !selectedKeys.value.includes(action))) {
        selectedKeys.value = selectedKeys.value.filter(key => key !== itemKey);
      }
    }
  }
};
</script>

<style scoped>
.perm-wrapper{
  min-width: 360px;
}
.perm-list-item {
  display: flex;
  cursor: default;
}
.border-top,
.perm-list-item + .perm-list-item {
  border-top: 1px solid #f0f0f0;
}

.perm-list-item-title {
  flex: 0 0 120px;
  padding: 8px 10px;
  display: flex;
  align-items: center;
}
.perm-list-group{
  border-radius: var(--border-radius);
  border:1px solid #f0f0f0;
  margin-bottom: var(--space);
}
.perm-list-group-title {
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.perm-list-item-content {
  border-left: 1px solid #f0f0f0;
  padding: 8px 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  flex: 1;
}
.perm-list-item:nth-child(odd) {
  background-color: #fafafa;
}
</style>